package dataStructure;

import java.util.Scanner;

public class QueueByArray {
    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(3);
        Scanner sc = new Scanner(System.in);
        Boolean loop = true;
        while (loop) {
            System.out.println("输入p，添加数据");
            System.out.println("输入g，取出数据");
            System.out.println("输入s，展示数据");
            System.out.println("输入e，退出");
            char s = sc.next().charAt(0);
            switch (s) {
                case 'p':
                    System.out.println("请输入一个数字");
                    int element = sc.nextInt();
                    try {
                        queue.putElement(element);
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                    break;
                case 'g':
                    try {
                        System.out.println(queue.getElement());
                    } catch (Exception e) {
                        System.out.println(e);
                    }

                    break;
                case 's':
                    queue.show();
                    break;
                case 'e':
                    loop = false;
                    break;
                default:
                    System.out.println("输入错误");
                    break;

            }
        }
    }
}

class ArrayQueue {
    private int near;//表示最后一个元素
    private int front;//表第一个元素
    private int maxLength;
    private int[] array;

    //构造函数
    public ArrayQueue(int length) {
        array = new int[length];
        maxLength = length;
        near = -1;
        front = -1;
    }

    //如果最后一个元素的下标+1对数组长度取余等于front的话，表示该队列已经满了
    public Boolean isFull() {
        return near - front == maxLength;
    }

    //如果第一个元素的下标的前一位也就是front的值等于near的时候，说明队列是空的
    public Boolean isEmpty() {
        return near == front ? true : false;
    }

    //取出数据
    public synchronized int getElement() {
        //先判断是不是空的
        if (isEmpty()) {
            throw new RuntimeException("队列是空的，不可以取出数据");
        }
        front++;
        return array[front % maxLength];
    }

    //往里面放数据
    public synchronized void putElement(int element) {
        //判断是不是满了
        if (isFull()) {
            throw new RuntimeException("队列已经满了，不可以加入队列");
        }
        near++;
        array[near % maxLength] = element;
    }

    //遍历队列中的数据
    public void show() {
        for (int i = front; i < near; i++) {
            System.out.println(array[(i + 1) % maxLength] + "   ");
        }
    }
}
